package com.example.campuslink.viewModel

import android.content.Intent
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.campuslink.commen.db.message.MessageTable
import com.example.campuslink.commen.db.userInfo.UserInfoTable
import com.example.campuslink.commen.db.userNumber.UserNumberTable
import com.example.campuslink.commen.enums.MessageTypeEnum
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.commen.tools.SpKey
import com.example.campuslink.commen.tools.putExtraKey
import com.example.campuslink.ui.activity.UserMainActivity
import com.example.campuslink.ui.activity.message.CollectationActivity
import com.example.campuslink.ui.activity.message.CommendAndCallActivity
import com.example.campuslink.ui.activity.message.NewAddAttentionActivity
import com.example.campuslink.ui.activity.userOperation.UserInfoActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MessageViewModel : BaseViewModel() {
    private val _schoolUserNumber = MutableLiveData<List<String>>()
    val schoolUserNumber get() = _schoolUserNumber
    private val _userInfoMap = MutableLiveData<HashMap<String, UserInfoTable>>()
    val userInfoMap: LiveData<HashMap<String, UserInfoTable>> = _userInfoMap
    private val _messageList = MutableLiveData<List<MessageTable>>()
    val messageList: LiveData<List<MessageTable>> = _messageList
    private val _messType = MutableLiveData<String>()
    val messType get() = _messType
    private val _attentionList = MutableLiveData<MutableList<String>>()
    val attentionList: LiveData<MutableList<String>> = _attentionList
    private val _fansList = MutableLiveData<MutableList<String>>()
    val fansList: LiveData<MutableList<String>> = _fansList

    fun setMessageType(type: String) {
        _messType.value = type
    }

    fun removeAttentionAndFans(userId: String) {
        viewModelScope.launch(Dispatchers.IO) {
            val userNumber = Sp.getString(context, SpKey.USER_NUMBER.key, "")
            val nowUserNumberTableInfo = userNumberDao.getUserNumber(userNumber ?: "")
            val otherUserNumberTableInfo = userNumberDao.getUserNumber(userId ?: "")
            nowUserNumberTableInfo?.followList?.removeAll { it == userId }
            otherUserNumberTableInfo?.fansList?.removeAll { it == userNumber }
            userNumberDao.updateUserNumber(nowUserNumberTableInfo ?: return@launch)
            userNumberDao.updateUserNumber(otherUserNumberTableInfo ?: return@launch)
            getAttentionListAndFansList()
            getNowSchoolNumberList()
        }
    }

    fun addAttentionAndFans(userId: String) {
        viewModelScope.launch(Dispatchers.IO) {
            val userNumber = Sp.getString(context, SpKey.USER_NUMBER.key, "")
            val nowUserNumberTableInfo = userNumberDao.getUserNumber(userNumber ?: "")
            val otherUserNumberTableInfo = userNumberDao.getUserNumber(userId ?: "")
            nowUserNumberTableInfo?.followList?.removeAll { it == userId }
            otherUserNumberTableInfo?.fansList?.removeAll { it == userNumber }
            nowUserNumberTableInfo?.followList?.add(userId)
            otherUserNumberTableInfo?.fansList?.add(userNumber ?: "")
            val schoolInfoTable =
                schoolInfoDao.getSchoolInfoBySchoolName(nowUserNumberTableInfo?.schoolName ?: "")
            if (schoolInfoTable != null) {
//                if (schoolInfoTable?.messageList == null || schoolInfoTable?.messageList?.size == 0) {
//                    schoolInfoTable.messageList = mutableListOf()
//                    schoolInfoDao.updateSchoolInfo(schoolInfoTable)
//                }
                var messageTable = MessageTable()
                messageTable.handNumber = userId
                messageTable.sendNumber = userNumber ?: ""
                messageTable.messageType = MessageTypeEnum.NEW_ADD_ATTENTION.value
                messageTable.messageTime = System.currentTimeMillis()
                messageTable.messageContent = "对方关注了你"
                messageTable.messageImage = ""
                MessageTable.insertWithId(messageDao, messageTable)
                schoolInfoTable?.messageList?.add(messageTable)
                schoolInfoDao.updateSchoolInfo(schoolInfoTable)
            }
            userNumberDao.updateUserNumber(nowUserNumberTableInfo ?: return@launch)
            userNumberDao.updateUserNumber(otherUserNumberTableInfo ?: return@launch)
            getAttentionListAndFansList()
            getNowSchoolNumberList()
        }
    }

    fun jumpToUserMainActivity(number:String){
        startActivity(Intent().apply {
            putExtra(putExtraKey.USER_NUMBER.key,number)
        },
            targetClass = UserMainActivity::class.java)
    }

    fun getAttentionListAndFansList() {
        viewModelScope.launch(Dispatchers.IO) {
            val userNumber = Sp.getString(context, SpKey.USER_NUMBER.key, "")
            val userNumberTableInfo = userNumberDao.getUserNumber(userNumber ?: "")
            _attentionList.postValue(userNumberTableInfo?.followList)
            _fansList.postValue(userNumberTableInfo?.fansList)
        }
    }

    fun deleteMessage(message: MessageTable) {
        viewModelScope.launch(Dispatchers.IO) {
            val schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(
                userNumberDao?.getUserNumber(
                    Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
                )?.schoolName ?: ""
            )
            if (schoolInfo != null) {
                schoolInfo.messageList.remove(message)
            }
            schoolInfoDao.updateSchoolInfo(schoolInfo)
            if (message.messageType == MessageTypeEnum.BE_LOVE_COMMENT.value) {
                getSupportCommendMessage()
            } else if (message.messageType == MessageTypeEnum.BE_LOVE_INVITATION.value) {
                getSupportInvitationMessage()
            } else if (message.messageType == MessageTypeEnum.CALL_YOUR.value) {
                getCallMessage()
            } else if (message.messageType == MessageTypeEnum.GET_COMMENT.value) {
                getCommentMessage()
            } else {
                getAttentionMessage()
            }
        }
    }

    fun getSupportInvitationMessage() {
        viewModelScope.launch(Dispatchers.IO) {
            val schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(
                userNumberDao?.getUserNumber(
                    Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
                )?.schoolName ?: ""
            )
            if (schoolInfo != null) {
                val temp = mutableListOf<MessageTable>()
                schoolInfo.messageList.forEach {
                    if (it.messageType == MessageTypeEnum.BE_LOVE_INVITATION.value && it.handNumber == Sp.getString(
                            context,
                            SpKey.USER_NUMBER.key,
                            ""
                        ) ?: ""
                    ) {
                        temp.add(it)
                    }
                }
                _messageList.postValue(temp.reversed())
            }
        }
    }

    fun getSupportCommendMessage() {
        viewModelScope.launch(Dispatchers.IO) {
            val schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(
                userNumberDao?.getUserNumber(
                    Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
                )?.schoolName ?: ""
            )
            if (schoolInfo != null) {
                val temp = mutableListOf<MessageTable>()
                schoolInfo.messageList.forEach {
                    if (it.messageType == MessageTypeEnum.BE_LOVE_COMMENT.value && it.handNumber == Sp.getString(
                            context,
                            SpKey.USER_NUMBER.key,
                            ""
                        ) ?: ""
                    ) {
                        temp.add(it)
                    }
                }
                _messageList.postValue(temp.reversed())
            }
        }
    }

    fun getAttentionMessage() {
        viewModelScope.launch(Dispatchers.IO) {
            val schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(
                userNumberDao?.getUserNumber(
                    Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
                )?.schoolName ?: ""
            )
            if (schoolInfo != null) {
                val temp = mutableListOf<MessageTable>()
                schoolInfo.messageList.forEach {
                    if (it.messageType == MessageTypeEnum.NEW_ADD_ATTENTION.value && it.handNumber == Sp.getString(
                            context,
                            SpKey.USER_NUMBER.key,
                            ""
                        ) ?: ""
                    ) {
                        temp.add(it)
                    }
                }
                _messageList.postValue(temp.reversed())
            }
        }
    }

    fun getCommentMessage() {
        viewModelScope.launch(Dispatchers.IO) {
            val schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(
                userNumberDao?.getUserNumber(
                    Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
                )?.schoolName ?: ""
            )
            if (schoolInfo != null) {
                val temp = mutableListOf<MessageTable>()
                schoolInfo.messageList.forEach {
                    if (it.messageType == MessageTypeEnum.GET_COMMENT.value && it.handNumber == Sp.getString(
                            context,
                            SpKey.USER_NUMBER.key,
                            ""
                        ) ?: ""
                    ) {
                        temp.add(it)
                    }
                }
                _messageList.postValue(temp.reversed())
            }
        }
    }

    fun getCallMessage() {
        viewModelScope.launch(Dispatchers.IO) {
            val schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(
                userNumberDao?.getUserNumber(
                    Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
                )?.schoolName ?: ""
            )
            if (schoolInfo != null) {
                val temp = mutableListOf<MessageTable>()
                schoolInfo.messageList.forEach {
                    if (it.messageType == MessageTypeEnum.CALL_YOUR.value && it.handNumber == Sp.getString(
                            context,
                            SpKey.USER_NUMBER.key,
                            ""
                        ) ?: ""
                    ) {
                        temp.add(it)
                    }
                }
                _messageList.postValue(temp.reversed())
            }
        }
    }

    fun getUserInfo(userId: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val userInfo = userInfoDao.getUserInfoByUserNumber(userId) ?: return@launch
                val currentMap = _userInfoMap.value ?: HashMap()
                currentMap[userId] = userInfo
                _userInfoMap.postValue(currentMap)
            } catch (e: Exception) {
                Log.e("TAG", "获取用户信息失败", e)
            }
        }
    }


    fun getNowSchoolNumberList() {
        val temp = mutableListOf<String>()
        viewModelScope.launch(Dispatchers.IO) {
            val userInfoTable =
                userNumberDao.getUserNumber(Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: "")
            if (userInfoTable != null) {
                val schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(userInfoTable.schoolName)
                schoolInfo?.schoolUser?.forEach {
                    if (it != Sp.getString(context, SpKey.USER_NUMBER.key, "") && it !in temp) {
                        temp.add(it)
                    }
                }
                _schoolUserNumber?.postValue(temp)
            }
        }
    }

    fun jumpToCollectionMessageActivity() {
        startActivity(Intent(), targetClass = CollectationActivity::class.java)
    }

    fun jumpToNewAttentionActivity() {
        startActivity(Intent(), targetClass = NewAddAttentionActivity::class.java)
    }

    fun finish() {
        finishActivity()
    }

    fun jumpToCommendAndCallActivity() {
        startActivity(Intent(), targetClass = CommendAndCallActivity::class.java)
    }

}